package com.css.fxfzaqbz.modules.data.controller;

import com.css.fxfzaqbz.base.response.RestResponse;
import com.css.fxfzaqbz.base.upload.entity.AttachmentInfoEntity;
import com.css.fxfzaqbz.base.upload.service.AttachmentInfoService;
import com.css.fxfzaqbz.modules.data.entity.ImportantActivity;
import com.css.fxfzaqbz.modules.data.entity.Region;
import com.css.fxfzaqbz.modules.data.entity.WorkerInfo;
import com.css.fxfzaqbz.modules.data.queryParams.ImportantActivityQueryParams;
import com.css.fxfzaqbz.modules.data.service.ImportantActivityService;
import com.css.fxfzaqbz.modules.supergraph.exception.CustomException;
import com.css.fxfzaqbz.util.CreateGson;
import com.css.fxfzaqbz.util.PlatformObjectUtils;
import com.css.fxfzaqbz.util.PlatformPageUtils;
import com.css.fxfzaqbz.web.PlatformSessionContext;
import com.css.fxfzaqbz.zcpt.sys.entity.SUser;
import com.css.fxfzaqbz.zcpt.sys.service.SysAreaService;
import com.css.fxfzaqbz.zcpt.sys.service.impl.SUserServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 重大活动信息表单接口
 */
@RestController
@RequestMapping("/fxfzaqbz/data")
@Slf4j
public class ImportantActivityController {

    @Resource
    ImportantActivityService importantActivityService;

    @Resource
    private SysAreaService sysAreaService;

    @Resource
    private SUserServiceImpl sUserServiceImpl;
    @Resource
    private AttachmentInfoService attachmentInfoService;


    /**
     * 获取新的活动 id
     *
     * @return map集合
     */
    @GetMapping("/getNewImportantActivityId")
    public RestResponse getNewIAId() {

        RestResponse restResponse = null;
        try {
            Map<String, String> map = new HashMap<>();
            map.put("nextSerialNo", importantActivityService.getNewIAId());
            restResponse = RestResponse.succeed(map);
        } catch (Exception e) {
            log.error("获取新的重大活动 id 失败", e);
            restResponse = RestResponse.fail("获取新的重大活动 id 失败!");
        }
        return restResponse;
    }

    /**
     * 新增importantActivity
     *
     * @param importantActivity
     * @return
     */
    @PostMapping("/saveImportantActivity")
    public RestResponse saveImportantActivity(@RequestBody ImportantActivity importantActivity) {
        RestResponse restResponse = null;

        try {
            String userID = PlatformSessionContext.getUserID();
            importantActivity.setCreateUser(userID);


            if (importantActivity.getProvinceId() != null) {
                String provinceId = importantActivity.getProvinceId();
                String province = sysAreaService.getAreaNameByAreaId(provinceId);
                importantActivity.setIaProvince(province);
            }

            if (importantActivity.getCityId() != null) {
                String provinceId = importantActivity.getProvinceId();
                String cityId = importantActivity.getCityId();
                String address = provinceId + "," + cityId;
                String areaNameByAreaId = sysAreaService.getAreaNameByAreaId(address);
                String[] split = areaNameByAreaId.split(",");
                importantActivity.setIaProvince(split[0]);
                importantActivity.setIaCity(split[1]);
            }
            if (importantActivity.getCountiesId() != null) {
                String provinceId = importantActivity.getProvinceId();
                String cityId = importantActivity.getCityId();
                String prefectureId = importantActivity.getCountiesId();
                String address = provinceId + "," + cityId + "," + prefectureId;
                String areaNameByAreaId = sysAreaService.getAreaNameByAreaId(address);
                String[] split = areaNameByAreaId.split(",");
                importantActivity.setIaProvince(split[0]);
                importantActivity.setIaCity(split[1]);
                importantActivity.setIaCounties(split[2]);
            }


            // 数据解析
            ImportantActivity importantActivity1 = iaDataParse(importantActivity);
            importantActivity1.setIaZddwYwry(importantActivity.getIaZddwYwry());


            restResponse = RestResponse.succeed(importantActivityService.saveImportantActivity(importantActivity1));

        } catch (Exception e) {
            log.error("新增重大活动信息失败", e);
            restResponse = RestResponse.fail("新增重大活动信息失败!");
        }
        return restResponse;
    }


    /**
     * 全查询  模糊查询未设定条件
     *
     * @param request
     * @param queryParams
     * @return
     */
    @GetMapping("/getAllImportantActivity")
    public RestResponse getAllImportantActivity(HttpServletRequest request,
                                                ImportantActivityQueryParams queryParams) {

        RestResponse restResponse = null;
        try {
            int curPage = Integer.valueOf(request.getParameter(PlatformPageUtils.CUR_PAGE));
            int pageSize = Integer.valueOf(request.getParameter(PlatformPageUtils.PAGE_SIZE));
            queryParams.setCurPage(curPage);
            queryParams.setPageSize(pageSize);
            Map<String, Object> allImportantActivity = importantActivityService.getAllImportantActivity(queryParams);
            if (allImportantActivity == null) {
                restResponse = RestResponse.fail("完善个人地址信息后查看");
            } else {
                restResponse = RestResponse.succeed(allImportantActivity);
            }

        } catch (Exception e) {
            log.error("查询重大活动信息失败!", e);
            restResponse = RestResponse.fail("查询重大活动信息失败");
        }
        return restResponse;
    }

    //查询全部
    @GetMapping("/getAllByRole")
    public RestResponse getAllByRole(HttpServletRequest request,
                                       ImportantActivityQueryParams queryParams) {

        RestResponse restResponse = null;
        try {
            int curPage = Integer.valueOf(request.getParameter(PlatformPageUtils.CUR_PAGE));
            int pageSize = Integer.valueOf(request.getParameter(PlatformPageUtils.PAGE_SIZE));
            queryParams.setCurPage(curPage);
            queryParams.setPageSize(pageSize);
            Map<String, Object> map = importantActivityService.getAll(queryParams);
            restResponse = RestResponse.succeed(map);
        } catch (CustomException e) {
            log.error(e.getMessage());
            restResponse = RestResponse.fail(e.getMessage());
        } catch (Exception e) {
            log.error("查询重大活动信息失败!", e);
            restResponse = RestResponse.fail("查询重大活动信息失败");
        }
        return restResponse;
    }

    /**
     * 根据id查询ImportantActivity数据
     *
     * @param id
     * @return
     */
    @GetMapping("/getImportantActivity/{id}")
    public RestResponse<ImportantActivity> getImportantActivity(@PathVariable String id) {
        RestResponse restResponse = null;
        try {
            ImportantActivity importantActivity = importantActivityService.getImportantActivityById(id);
            ImportantActivity importantActivity1 = iaDataParse(importantActivity);
            List<String> wjtzs = importantActivity1.getWjtzs();
            Map<String, Object> map = new HashMap<>();
            if (wjtzs != null) {
                List<AttachmentInfoEntity> list = new ArrayList<>();
                AttachmentInfoEntity attach;
                for (String wjtz : wjtzs) {
                    try {
                        attach = attachmentInfoService.getAttach(wjtz);
                    } catch (Exception e) {
                        attach = null;
                    }
                    list.add(attach);
                }
                map.put("list", list);
            }

            map.put("importantActivity", importantActivity1);
            restResponse = RestResponse.succeed(map);
        } catch (Exception e) {
            log.error("获取重大活动信息失败!", e);
            restResponse = RestResponse.fail("获取重大活动信息失败!");
        }
        return restResponse;
    }


    /**
     * 逻辑删除，修改数据标志位
     *
     * @param ids
     * @return
     */
    @PostMapping("/delImportantActivity/{ids}")
    public RestResponse deleteImportantActivity(@PathVariable("ids") List<String> ids) {
        RestResponse restResponse = null;
        try {
            String userID = PlatformSessionContext.getUserID();
            importantActivityService.deleteImportantActivitys(ids, userID);
            restResponse = RestResponse.succeed();
        } catch (Exception e) {
            log.error("删除重大活动信息失败!", e);
            restResponse = RestResponse.fail("删除重大活动信息失败!");
        }
        return restResponse;
    }

    /**
     * 修改
     *
     * @param importantActivity
     * @return
     */
    @PostMapping("/updateImportantActivity")
    public RestResponse<ImportantActivity> updateImportantActivity(@RequestBody ImportantActivity importantActivity) {
        RestResponse restResponse = null;
        try {

            if (importantActivity.getProvinceId() != null) {
                String provinceId = importantActivity.getProvinceId();
                String province = sysAreaService.getAreaNameByAreaId(provinceId);
                importantActivity.setIaProvince(province);
            }

            if (importantActivity.getCityId() != null) {
                String provinceId = importantActivity.getProvinceId();
                String cityId = importantActivity.getCityId();
                String address = provinceId + "," + cityId;
                String areaNameByAreaId = sysAreaService.getAreaNameByAreaId(address);
                String[] split = areaNameByAreaId.split(",");
                importantActivity.setIaProvince(split[0]);
                importantActivity.setIaCity(split[1]);
            }
            if (importantActivity.getCountiesId() != null) {
                String provinceId = importantActivity.getProvinceId();
                String cityId = importantActivity.getCityId();
                String prefectureId = importantActivity.getCountiesId();
                String address = provinceId + "," + cityId + "," + prefectureId;
                String areaNameByAreaId = sysAreaService.getAreaNameByAreaId(address);
                String[] split = areaNameByAreaId.split(",");
                importantActivity.setIaProvince(split[0]);
                importantActivity.setIaCity(split[1]);
                importantActivity.setIaCounties(split[2]);
            }

         /*   String provinceId = importantActivity.getProvinceId();
            String cityId = importantActivity.getCityId();
            String prefectureId = importantActivity.getCountiesId();
            String address = provinceId + "," + cityId + "," + prefectureId;
            String areaNameByAreaId = sysAreaService.getAreaNameByAreaId(address);
            String[] split = areaNameByAreaId.split(",");
            importantActivity.setIaProvince(split[0]);
            importantActivity.setIaCity(split[1]);
            importantActivity.setIaCounties(split[2]);*/

            //获取用户名称
            String sUser = sUserServiceImpl.getSUser(PlatformSessionContext.getUserID());
            SUser userInfo = CreateGson.createGson().fromJson(sUser, SUser.class);
            String userName = userInfo.getUserName();
            //  String userName = "测试1";
            ImportantActivity importantActivity1 = iaDataParse(importantActivity);
            restResponse = RestResponse.succeed(importantActivityService.updateImportantActivity(importantActivity1));
        } catch (Exception e) {
            log.error("修改重大活动信息失败!", e);
            restResponse = RestResponse.fail("修改重大活动信息失败!");
        }
        return restResponse;
    }


    /**
     * 根据ID修改地震趋势会商建议
     *
     * @param importantActivity
     * @return
     */
    @PostMapping("/updateOpinion")
    public RestResponse<ImportantActivity> updateOpinion(@RequestBody ImportantActivity importantActivity) {
        RestResponse restResponse = null;
        try {

            //获取用户名称
//            String sUser = sUserServiceImpl.getSUser(PlatformSessionContext.getUserID());
//            SUser userInfo = CreateGson.createGson().fromJson(sUser, SUser.class);
//            String userName = userInfo.getUserName();
//            importantActivity.setCreateUser(userName);
            ImportantActivity importantActivity1 = iaDataParse(importantActivity);
            restResponse = RestResponse.succeed(importantActivityService.updateImportantActivity(importantActivity1));
        } catch (Exception e) {
            log.error("修改修改地震趋势会商建议失败!", e);
            restResponse = RestResponse.fail("修改修改地震趋势会商建议失败!");
        }
        return restResponse;
    }


//    /**
//     * 导出表内数据
//     * @param response
//     * @throws IOException
//     */
//    @PostMapping("/exportExcelActiveFaultData")
//    public void exportExcel(HttpServletResponse response ) throws IOException {
//        RestResponse restResponse = null;
//        try{
//            List<ActiveFaultData> list  = activeFaultDataService.getAll();
//            FileUtil.exportExcel(list, "活动断层数据", "sheet", ActiveFaultData.class, "ActiveFaultData", response);
//            restResponse = RestResponse.succeed("导出成功");
//        }catch (Exception e){
//            log.error("导出失败",e);
//            restResponse = RestResponse.fail("导出失败");
//        }
//    }
//
//    /**
//     * 导入数据
//     * @param file
//     * @throws IOException
//     */
//    @PostMapping("/importExcelActiveFaultData")
//    public RestResponse importExcel(MultipartFile file) throws IOException {
//        RestResponse restResponse = null;
//        try{
//            activeFaultDataService.importExcel(file);
//            restResponse = RestResponse.succeed("导入成功");
//        }catch (Exception e){
//            log.error("导入失败",e);
//
//        }
//        return restResponse ;
//    }


//    /* @param response
//     * @throws IOExceptiond
//     */
//    @PostMapping("/downLoadFile")
//    public void exportExcel(HttpServletResponse response,@RequestParam("attachId") String attachId ) {
//            System.out.println("attachId111");
//            System.out.println(attachId);
//            AttachmentInfoEntity attachmentInfoEntity = attachmentInfoRepository.getById(attachId);
//
//            String path = attachmentInfoEntity.getFileDirId()+attachmentInfoEntity.getAttachPath();
//            //String path = "D:\static\2022\09\07\q_1662518879720.png";
//            FileUploadUtil.download(path,response);
//
//    }

    @GetMapping("/searchList")
    public RestResponse<ImportantActivity> searchList(ImportantActivityQueryParams queryParams) {
        RestResponse restResponse = null;
        try {
            restResponse = RestResponse.succeed(importantActivityService.searchList(queryParams));
        } catch (Exception e) {
            log.error("查询重大活动信息失败!", e);
            restResponse = RestResponse.fail("查询重大活动信息失败");
        }
        return restResponse;
    }

    public ImportantActivity iaDataParse(ImportantActivity importantActivity) {
        if (null == importantActivity) {
            return null;
        }

        // 解析重点目标
        if (null != importantActivity.getZdmbs() && importantActivity.getZdmbs().size() > 0) {
            StringBuilder ans = listToString(importantActivity.getZdmbs());
            importantActivity.setIaZdmb(ans.toString());
        } else {
            if (!StringUtils.isBlank(importantActivity.getIaZdmb())) {
                String[] files = importantActivity.getIaZdmb().split(",");
                importantActivity.setZdmbs(Arrays.asList(files));
            }
        }

        // 解析文件列表 List
        if (null != importantActivity.getWjtzs() && importantActivity.getWjtzs().size() > 0) {
            StringBuilder ans = listToString(importantActivity.getWjtzs());
            importantActivity.setIaWjtz(ans.toString());
        } else {
            if (null != importantActivity.getIaWjtz() && !"".equals(importantActivity.getIaWjtz())) {
                String[] files = importantActivity.getIaWjtz().split(",");
                importantActivity.setWjtzs(Arrays.asList(files));
            }
        }

        // 解析指导单位业务人员
        if (null != importantActivity.getZddwYwrys() && importantActivity.getZddwYwrys().size() > 0) {
            importantActivity.setIaZddwYwrys(workInfoToStr(importantActivity.getZddwYwrys()).toString());
        } else {
            if (null != importantActivity.getIaZddwYwrys() && !"".equals(importantActivity.getIaZddwYwrys())) {
                importantActivity.setZddwYwrys(workInfoStrToList2(importantActivity.getIaZddwYwrys()));
            }
        }

        // 解析执行单位业务人员
        if (null != importantActivity.getSsdwYwrys() && importantActivity.getSsdwYwrys().size() > 0) {
            importantActivity.setIaSsdwYwrys(workInfoToStr(importantActivity.getSsdwYwrys()).toString());
        } else {
            if (null != importantActivity.getIaSsdwYwrys() && !"".equals(importantActivity.getIaSsdwYwrys())) {
                importantActivity.setSsdwYwrys(workInfoStrToList2(importantActivity.getIaSsdwYwrys()));
            }
        }

        // 解析协同单位业务人员
        if (null != importantActivity.getXtdwYwrys() && importantActivity.getXtdwYwrys().size() > 0) {
            importantActivity.setIaXtdwYwrys(workInfoToStr(importantActivity.getXtdwYwrys()).toString());
        } else {
            if (null != importantActivity.getIaXtdwYwrys() && !"".equals(importantActivity.getIaXtdwYwrys())) {
                importantActivity.setXtdwYwrys(workInfoStrToList2(importantActivity.getIaXtdwYwrys()));
            }
        }
        return importantActivity;
    }

    private StringBuilder listToString(List<String> list) {
        StringBuilder ans = new StringBuilder();
        for (String wjtz : list) {
            ans.append(wjtz).append(",");
        }
        if (ans.length() > 0) {
            ans.deleteCharAt(ans.length() - 1);
        }
        return ans;
    }


//    private StringBuilder listToStr(List<String> list) {
//        StringBuilder ans = new StringBuilder();
//        for (String wjtz : list) {
//            ans.append(wjtz).append(",");
//        }
//        if (ans.length() > 0) {
//            ans.deleteCharAt(ans.length() - 1);
//        }
//        return ans;
//    }

    private List<WorkerInfo> workInfoStrToList(String workerInfoStr) {
        List<WorkerInfo> workerInfos = new ArrayList<>();
        String[] workerInfoStrs = workerInfoStr.split(",");
        for (String workerInfo : workerInfoStrs) {
            WorkerInfo worker = new WorkerInfo();
            String[] infos = workerInfo.split("&");
            for (String info : infos) {
                if (StringUtils.isBlank(worker.getId())) {
                    worker.setId(info);
                } else if (StringUtils.isBlank(worker.getName())) {
                    worker.setName(info);
                } else {
                    if (CollectionUtils.isEmpty(worker.getDuties())) {
                        List<String> duties = new ArrayList<>();
                        duties.add(info);
                        worker.setDuties(duties);
                    } else {
                        worker.getDuties().add(info);
                    }
                }
                if (StringUtils.isBlank(worker.getName())) {
                    worker.setName(info);
                }
            }
            workerInfos.add(worker);
        }
        return workerInfos;
    }

    private List<WorkerInfo> workInfoStrToList2(String workerInfoStr) {
        List<WorkerInfo> workerInfos = new ArrayList<>();
        String[] workerInfoStrs = workerInfoStr.split(",");
        for (String workerInfo : workerInfoStrs) {
            WorkerInfo worker = new WorkerInfo();
            String[] infos = workerInfo.split("&");
            if (infos.length == 2) {
                worker.setId(infos[0]);
                worker.setName(infos[1]);
                workerInfos.add(worker);
            }
            if (infos.length == 3) {
                worker.setId(infos[0]);
                worker.setName(infos[1]);
                List<String> duties = new ArrayList<>();
                duties.add(infos[2]);
                worker.setDuties(duties);
                workerInfos.add(worker);
            }
            if (infos.length == 4) {
                worker.setId(infos[0]);
                worker.setName(infos[1]);
                List<String> duties = new ArrayList<>();
                duties.add(infos[2]);
                duties.add(infos[3]);
                worker.setDuties(duties);
                workerInfos.add(worker);
            }
            if (infos.length == 5) {
                worker.setId(infos[0]);
                worker.setName(infos[1]);
                List<String> duties = new ArrayList<>();
                duties.add(infos[2]);
                duties.add(infos[3]);
                duties.add(infos[4]);
                worker.setDuties(duties);
                workerInfos.add(worker);
            }
        }
        return workerInfos;
    }

    private StringBuilder workInfoToStr(List<WorkerInfo> workerInfos) {
        StringBuilder ans = new StringBuilder();
        for (WorkerInfo workerInfo : workerInfos) {
            ans.append(workerInfo.getId()).append("&");
            ans.append(workerInfo.getName()).append("&");
            if (null != workerInfo.getDuties() && workerInfo.getDuties().size() > 0) {
                for (String duty : workerInfo.getDuties()) {
                    ans.append(duty).append("&");
                }
            }
            if (ans.length() > 0) {
                ans.deleteCharAt(ans.length() - 1);
            }
            ans.append(",");
        }
        if (ans.length() > 0) {
            ans.deleteCharAt(ans.length() - 1);
        }
        return ans;
    }

    @GetMapping("/getAllActivity")
    public RestResponse getAllActivity() {

        RestResponse restResponse = null;
        try {
            List<ImportantActivity> allActivity = importantActivityService.getAllActivity();
            restResponse = RestResponse.succeed(allActivity);
        } catch (Exception e) {
            log.error("查询重大活动信息失败!", e);
            restResponse = RestResponse.fail("查询重大活动信息失败");
        }
        return restResponse;
    }

    /*
     * 活动已完成修改状态接口
     *
     * */
    @PostMapping("/updateActivityEndStatus/{iaId}")
    public RestResponse updateActivityEndStatus(@PathVariable("iaId") String iaId) {

        RestResponse restResponse = null;
        try {
            importantActivityService.updateActivityEndStatus(iaId);
            restResponse = RestResponse.succeed("活动已结束");
        } catch (Exception e) {
            log.error("活动已完成修改状态失败!", e);
            restResponse = RestResponse.fail("活动已完成修改状态失败");
        }
        return restResponse;
    }

    @GetMapping("/getAllSiteName")
    public RestResponse getAllSiteName(String province, String city, String counties) {
        RestResponse restResponse = null;
        try {
            List<String> siteList = importantActivityService.getAllSiteName(province, city, counties);
            restResponse = RestResponse.succeed(siteList);
        } catch (Exception e) {
            log.error("查询所有重点场所名字失败!", e);
            restResponse = RestResponse.fail("查询所有重点场所名字失败");
        }
        return restResponse;
    }

    @GetMapping("/getAllSiteName1")
    public RestResponse getAllSiteName1(Region region) {
        RestResponse restResponse = null;
        try {
            region.setProvince(sysAreaService.getAreaNameByAreaId(region.getProvince()));
            if (PlatformObjectUtils.isNotEmpty(region.getCity())) {
                region.setCity(sysAreaService.getAreaNameByAreaId(region.getCity()));
            } else {
                region.setCity(null);
            }
            if (PlatformObjectUtils.isNotEmpty(region.getCounty())) {
                region.setCounty(sysAreaService.getAreaNameByAreaId(region.getCounty()));
            } else {
                region.setCounty(null);
            }
            List<String> siteList = importantActivityService.getAllSiteName1(region);
            restResponse = RestResponse.succeed(siteList);
        } catch (Exception e) {
            log.error("查询所有重点场所名字失败!", e);
            restResponse = RestResponse.fail("查询所有重点场所名字失败");
        }
        return restResponse;
    }


    @GetMapping("/getCodeByIaId/{iaId}")
    public RestResponse getCodeByIaId(@PathVariable("iaId") String iaId) {
        RestResponse restResponse = null;
        try {
            restResponse = RestResponse.succeed(importantActivityService.getCodeByIaId(iaId));
        } catch (Exception e) {
            log.error("查询失败!", e);
            restResponse = RestResponse.fail("查询失败");
        }
        return restResponse;
    }

    //获取权限
    @GetMapping("/getRole")
    public RestResponse getRole(){
        RestResponse restResponse = null;
        try {
            restResponse = RestResponse.succeed(importantActivityService.getRole());
        } catch (Exception e) {
            log.error("获取权限失败!", e);
            restResponse = RestResponse.fail("获取权限失败");
        }
        return restResponse;
    }

    //是否进入审核流程  返回 0没有进入   1已开始审核
    @GetMapping("/getExamine")
    public RestResponse getExamine(String iaId){
        RestResponse restResponse = null;
        try {
            restResponse = RestResponse.succeed(importantActivityService.getExamine(iaId));
        } catch (Exception e) {
            log.error("获取权限失败!", e);
            restResponse = RestResponse.fail("获取权限失败");
        }
        return restResponse;
    }

}
